<?php
	require_once('includes.php');
	
	$client = new apiClient();
	$client->setApplicationName('Google Calendar for Health Tracker');
	$client->setUseObjects(true);
	
	$service = new apiCalendarService($client);
	//check when session are set to logout
	if (isset($_GET['logout'])) {
		unset($_SESSION['token']);
	}
	//retreive a code for authentication
	if (isset($_GET['code'])) {
		$client->authenticate();
		$_SESSION['token'] = $client->getAccessToken();
		header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
	}
	//check token on the session.
	if (isset($_SESSION['token'])) {
		$client->setAccessToken($_SESSION['token']);
	}
	//if AccessToken has been set on the client
	if($client->getAccessToken()) {
	
		//retreive all available calendar on user
		$calList = $service->calendarList->listCalendarList();
		
		//search a generated calendar from our system
		while(true) {
			foreach ($calList->getItems() as $calendarListEntry) {
				$title = $calendarListEntry->getSummary();
				if($title !== 'dangertracker') {
					$found = false;
				} else {
					$found = true;
					break;
				}
			}
			$pageToken = $calList->getNextPageToken();
			if ($pageToken) {
				$optParams = array('pageToken' => $pageToken);
				$calList = $calList->calendarList->listCalendarList($optParams);
			} else {
				break;
			}
		}
		
		//if not found create a new generated calendar
		if($found === false) {
			$calendar = new Calendar();
			$calendar->setSummary('dangertracker');
			
			$service->calendars->insert($calendar);
		}
		$_SESSION['token'] = $client->getAccessToken();
	}
	
?>